<?php

namespace app\controllers;

use app\models\Fbx;
use app\models\Image;
use Yii;
use app\models\Model;
use app\models\ModelSearch;
use app\models\Data;
use app\models\DataSearch;
use yii\base\ErrorException;
use yii\bootstrap\Html;
use yii\data\Pagination;
use yii\helpers\Url;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use app\models\UserBackend;

/**
 * ModelController implements the CRUD actions for Model model.
 */
class ModelController extends Controller
{

    static public function getFullPath($model)
    {
        return Url::home(true) . $model->location;
    }

    public function actionSearchcount($keywords)
    {
        $query = Fbx::find()->andFilterWhere(["like", "name", $keywords])->orFilterWhere(["like", "code", $keywords]);
        return $query->count();
    }

    public function actionSearch($keywords, $count)
    {
        $query = Fbx::find()->andFilterWhere(["like", "name", $keywords])->orFilterWhere(["like", "code", $keywords]);
        $pages = new Pagination(['totalCount' => $query->count(), 'pageSize' => $count]);
        $models = $query->offset($pages->offset)->limit($pages->limit)->all();
        $data = self::convertDatabaseToJsonabelArr($models);
        return json_encode(
            ['jsonInfo' => ['modelsInfo' => $data, 'total' => $query->count(), 'json_date' => Yii::$app->params['date']]]
        );
    }


    static public function convertDatabaseToJsonabelArr($models)
    {
        $data = [];
        for ($i = 0; $i != count($models); $i++) {
            $data[$i] = [
                'id' => $models[$i]->id,
                'name' => $models[$i]->name,
                'category_id' => $models[$i]->category_id,
                'url' => Html::encode(ModelController::getFullPath($models[$i])),
                'imageUrl' => Html::encode(Url::home(true) . $models[$i]->img_url),
                'updateDate' => $models[$i]->update_date,
                'version' => $models[$i]->version,
            ];
        }
        return $data;
    }

    static public function getJsonAsset($displayModelCount, $userName, $type = 'fbx')
    {
        $total = 0;
        $data = [];
        $user_Id = UserBackend::find()->select('id')->where(['username' => $userName])->scalar();

        if ($type == 'fbx') {
            $query = Fbx::find()->filterWhere(['type' => 'FBX', 'author_id' => $user_Id])->orderBy(['id' => SORT_DESC]);
            $allModels = $query->all();
            $pages = new Pagination(['totalCount' => $query->count(), 'pageSize' => $displayModelCount]);
            $pagination = $pages->pageCount;
            $models = array_slice($allModels, $pages->offset, $pages->limit);
            $total = $query->count();
            if (Yii::$app->params['date'] == '') {
                Yii::$app->params['date'] = date('Y-m-d H:i:s');
            }
            $data = self::convertDatabaseToJsonabelArr($models, $pagination);
        }
        return [$data, $total];
    }

    public function actionCount($category_id = 1)
    {
        return $this->getJsonAsset($category_id, 1)[1];
    }

    /**
     * @param int $count
     * @param $userName
     * @param string $type
     * @return false|string
     */
    public function actionJsonasset($count = 15, $userName, $type = 'fbx')
    {
        $user_Id = UserBackend::find()->select('id')->where(['username' => $userName])->scalar();
        $query = Fbx::find()->filterWhere(['type' => 'FBX', 'author_id' => $user_Id])->orderBy(['id' => SORT_DESC]);
        $pages = new Pagination(['totalCount' => $query->count(), 'pageSize' => $count]);
        $data = $this->getJsonAsset($count, $userName, $type)[0];

        return json_encode(
            ['jsonInfo' => ['modelsInfo' => $data, 'json_date' => Yii::$app->params['date'], 'pageCount' => $pages->pageCount]]
        );
    }

    public function actionJson($id)
    {
        $model = Model::findOne($id);
        $data = [
            'id' => $model->id,
            'name' => $model->name,
            'url' => Html::encode($this::getFullPath($model)),
            'imageUrl' => Html::encode(Url::home(true) . $model->img_url),
            'updateDate' => $model->update_date,
            'version' => $model->version,
        ];
        echo json_encode(['modelInfo' => $data]);
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all ProofModel models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new DataSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single ProofModel model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new ProofModel model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Model();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing ProofModel model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException
     * @throws \yii\db\StaleObjectException
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing fbx.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException
     * @throws \yii\db\StaleObjectException
     */
    public function actionDelete($id)
    {
        $fbx = Fbx::findOne(['img_url' => $id]);
        $image = Image::findOne(['img_url' => $id]);

        if ($fbx !== null && $image !== null) {
            try {
                $fbx_local = str_replace('\\','/',dirname(dirname(__FILE__)) . '\web' . '\\' . $fbx->location);
                $img_local = str_replace('\\','/',dirname(dirname(__FILE__)) . '\web' . '\\' . $image->location);
                unlink($fbx_local);
                unlink($img_local);
                $fbx->delete();
                $image->delete();
            } catch (ErrorException $e) {
                echo 'Caught exception: ', $e->getMessage(), "\n";
            }
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        return $this->redirect(['index']);
    }

    /**
     * Finds the ProofModel model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param $img_url
     * @return bool the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     * @throws \yii\db\StaleObjectException
     */
    protected function findModel($img_url)
    {
        $fbx = Fbx::findOne(['img_url' => $img_url]);
        $image = Image::findOne(['img_url' => $img_url]);

        if ($fbx !== null && $image !== null) {
            $fbx->delete();
            $image->delete();
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
        return true;
    }
}
